<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">用户管理</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a th:href="@{admin}">首页</a></li>
                    <li class="breadcrumb-item active">权限管理</li>
                    <li class="breadcrumb-item active">用户管理</li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
    <div class="card card-info">
        <shiro:hasPermission name="user:list">
            <form id="searchForm" class="needs-validation form-inline" novalidate="">
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" class="form-control m-2" id="username">
                </div>
                <div class="form-group">
                    <label for="email">邮箱:</label>
                    <input type="text" class="form-control m-2" id="email">
                </div>
                <div class="form-group">
                    <label for="phone">电话:</label>
                    <input type="tel" class="form-control m-2" id="phone">
                </div>
                <div class="form-group">
                    <button class="btn btn-primary ml-3" type="submit">查询</button>
                    <button class="btn btn-default ml-2" type="reset">重置</button>
                </div>
            </form>
        </shiro:hasPermission>
    </div>
    <div class="card card-body">
        <div id="toolbar" class="btn-group">
            <shiro:hasPermission name="user:add">
                <button id="btn_add" type="button" class="btn btn-primary">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                </button>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:batchDelete">
                <button id="btn_batch_delete" type="button" class="btn btn-danger">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>批量删除
                </button>
            </shiro:hasPermission>
        </div>
        <table class="table-sm" id="table"></table>
    </div>
</section>


<!-- 表单模态框 -->
<section id="formModalWrapper">
    <div class="modal fade" id="formModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="formTitle"></h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="formContent"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveOrUpdateBtn">保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 角色分配模态框 -->
<section id="assignRoleModalWrapper">
    <div class="modal fade" id="assignRoleModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="assignRoleTitle">分配角色</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <table id="assignRoleTable"></table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="assignRoleSaveOrUpdateBtn">保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>

<script>

    $(function () {

        var editFlag = Core.parseBool("[[${@perms.hasPerm('user:edit')}]]");
        var deleteFlag = Core.parseBool("[[${@perms.hasPerm('user:delete')}]]");
        var assignRoleFlag = Core.parseBool("[[${@perms.hasPerm('user:assignRole')}]]");

        window.operateEvents = {
            // 点击编辑
            'click .btn_edit': function (e, value, row, index) {
                editRow(row.userId)
            },
            // 点击分配角色
            'click .btn_assign': function (e, value, row, index) {
                assignRole(row.userId)
            },
            // 点击删除
            'click .btn_del': function (e, value, row, index) {
                deleteRow(row.userId)
            }
        }
        var columns = [
            {checkbox: true},
            {
                field: 'username',
                title: '用户名',
                align: "center"
            }, {
                field: 'email',
                title: '邮箱',
                align: "center"
            }, {
                field: 'phone',
                title: '电话',
                align: "center",
            }, {
                field: 'roles',
                title: '角色',
                align: "center",
                formatter: function (value, row, index) {
                    var roles = "";
                    $.each(value, function (i, item) {
                        roles += item.name + ",";
                    })
                    if (roles !== "") {
                        roles = roles.substr(0, roles.length - 1);
                    }
                    return roles;
                }
            },
            {
                field: 'status',
                title: '用户状态',
                align: "center",
                formatter: function (value, row, index) {
                    return row.status ? "启用" : "禁用";
                }
            },
            {
                field: 'operation',
                title: '操作',
                align: "center",
                width: 200,
                events: operateEvents,
                formatter: operationFormatter
            }];

        function operationFormatter(value, row, index) {
            var edit = editFlag ? '<button class="btn btn-info btn-sm btn_edit">编辑</button>' : '';
            var assign = assignRoleFlag ? '<button class="btn btn-info btn-sm ml-1 btn_assign">分配角色</button>' : '';
            var del = deleteFlag ? '<button class="btn btn-danger btn-sm ml-1 btn_del">删除</button>' : '';
            return edit + assign + del;
        }

        var options = {
            id: "#table",
            url: '/user/list',
            columns: columns,
            toolbar: '#toolbar',
            showRefresh: true,
            queryParams: queryParams
        }
        Core.initTable(options);

        function refreshTable() {
            Core.refreshTable("#table")
        }

        // 查询参数
        function queryParams(params) {
            return {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                username: $("#username").val(),
                email: $("#email").val(),
                phone: $("#phone").val()
            };
        }

        // 查询
        $('#searchForm').submit(function (event) {
            event.preventDefault();
            event.stopPropagation();
            refreshTable();
        })

        // 新增
        $('#btn_add').on('click', function () {
            Core.load("#formContent", "/user/add", function () {
                $('#formTitle').text('新增')
                $("#formModal").modal('show');
            }, 2);
        })

        // 编辑
        function editRow(id) {
            Core.load("#formContent", "/user/edit?userId=" + id, function () {
                $('#formTitle').text('编辑')
                $("#formModal").modal('show');
            }, 2);
        }

        // 删除
        function deleteRow(userId) {
            Core.confirm("确定删除？", function () {
                Core.postAjax("/user/delete", {"userId": userId}, function (data) {
                    if (data.status === 200) {
                        refreshTable();
                    }
                    layer.msg(data.msg);
                })
            })
        }

        // 批量删除
        $("#btn_batch_delete").on('click', function () {
            var checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                Core.confirm("确定删除选中的" + checkedRows.length + "条记录？", function () {
                    var ids = [];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.userId);
                    })
                    Core.postAjax("/user/batch/delete", {"ids": ids}, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                        }
                        layer.msg(data.msg);
                    })
                })
            }
        })

        // 保存或更新
        $('#saveOrUpdateBtn').on('click', function () {
            var $f = $('#userForm');
            var valid = $f[0].checkValidity();
            var url = $f.find("input[name='userId']").val() ? "/user/edit" : "/user/add"
            if (valid) {
                Core.mask("#saveOrUpdateBtn");
                Core.postAjax(url, $f.serialize(), function (data) {
                    Core.unmask("#saveOrUpdateBtn");
                    if (data.status === 200) {
                        $("#formModal").modal("hide");
                        refreshTable();
                    }
                    layer.msg(data.msg);
                }, function () {
                    Core.unmask("#saveOrUpdateBtn");
                })
            }
            $f.addClass("was-validated")
        })

        var selectRoleIds;
        var userIdChecked;
        var loadRoleCount = 0;

        // 分配角色
        function assignRole(userId) {
            userIdChecked = userId;
            if (loadRoleCount === 0) {
                var roleColumns = [
                    {checkbox: true},
                    {
                        field: 'name',
                        title: '角色名称',
                        align: "center"
                    }, {
                        field: 'description',
                        title: '角色描述',
                        align: "center"
                    },
                    {
                        field: 'status',
                        title: '角色状态',
                        align: "center",
                        formatter: function (value, row, index) {
                            return row.status ? "有效" : "删除";
                        }
                    }];
                var roleOptions = {
                    id: "#assignRoleTable",
                    url: "/user/assign/role/list",
                    columns: roleColumns,
                    pagination: false,
                    queryParams: {
                        userId: userId
                    },
                    onLoadSuccess: function () {
                        loadRoleCount = 1;
                        Core.checkTableBy("#assignRoleTable", {field: "roleId", values: selectRoleIds});
                    },
                    responseHandler: handleRoleData,
                }
                Core.initTable(roleOptions);
            }
            if (loadRoleCount === 1) {
                Core.refreshTable("#assignRoleTable");
            }
            $("#assignRoleModal").modal("show");
        }

        function handleRoleData(res) {
            selectRoleIds = res.hasRoles;
            return res.rows;
        }

        $('#assignRoleSaveOrUpdateBtn').on('click', function () {
            var checkedRows = Core.selectMutiData("#assignRoleTable");
            if (checkedRows) {
                Core.mask("#assignRoleSaveOrUpdateBtn");
                roleIdStr = "";
                $.each(checkedRows, function (i, item) {
                    roleIdStr += (item.roleId + ",");
                })
                roleIdStr = roleIdStr.substring(0, roleIdStr.length - 1);
                Core.postAjax('/user/assign/role', {userId: userIdChecked, roleIdStr: roleIdStr}, function (data) {
                    Core.unmask("#assignRoleSaveOrUpdateBtn");
                    if (data.status === 200) {
                        $("#assignRoleModal").modal("hide");
                        Core.refreshTable("#table");
                    }
                    layer.msg(data.msg);
                }, function (xhr) {
                    Core.unmask("#assignPermissionSaveOrUpdateBtn");
                    console.log(xhr)
                    layer.msg('保存失败')
                })
            }
        })

    });

</script>